#include <cstring>
#include <sstream>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/errno.h>
#include <linux/rtc.h>
#include <fcntl.h>
#include <unistd.h>
#include "m01_rtc.h"

namespace igslib
{
    M01RTCTimer::M01RTCTimer()
    {
        const std::string node_name = "/dev/rtc0";
        this->node_name = node_name;
        fd = open(this->node_name.c_str(),O_RDWR);
        if (fd < 0)
        {
            std::stringstream ss;
            ss << "Open device `" << this->node_name << "` failed.";
            throw_igslib_exception(ss.str());
        }
    }
    M01RTCTimer::~M01RTCTimer()
    {
        close(fd);
    }
    struct tm M01RTCTimer::GetTime()
    {
        rtc_time t;
        int fr = ioctl(fd, RTC_RD_TIME, &t);
        if (fr < 0)
        {
            memset(sti,0,sizeof(struct tm));
            std::stringstream ss;
            ss << "ioctl fail on get time.";
            util::Log(ss.str().c_str());
            return *sti;
        }
        t.tm_mon += 1;
        t.tm_year += 1900;
        sti->tm_sec = t.tm_sec;
        sti->tm_min = t.tm_min;
        sti->tm_hour = t.tm_hour;
        sti->tm_mday = t.tm_mday;
        sti->tm_mon = t.tm_mon;
        sti->tm_year = t.tm_year;
        return CRTCTimer::GetTime();
    }
    int M01RTCTimer::SetTime(struct tm value)
    {
        int rtn = 0;
        CRTCTimer::SetTime(value);

        rtc_time t;
        memset(&t,0,sizeof(rtc_time));
        t.tm_sec = sti->tm_sec;
        t.tm_min = sti->tm_min;
        t.tm_hour = sti->tm_hour;
        t.tm_mday = sti->tm_mday;
        t.tm_mon = sti->tm_mon-1;
        t.tm_year = sti->tm_year-1900;
		int fr = ioctl(fd,RTC_SET_TIME,&t);
        if (fr < 0)
        {
            std::stringstream ss;
			//ss << "Year:" << t.tm_year << " Month:" << t.tm_mon << " Date:" << t.tm_mday << "Hour:" << t.tm_hour << " Minute:" << t.tm_min << " Second:" << t.tm_sec;
            ss << "ioctl fail on set time. " << fr;
            util::Log(ss.str().c_str());
            rtn = -1;
        }
        return rtn;
    }
};
